/*
 * Copyright 2020-2021 redragon.dongbin
 *
 * This file is part of redragon-erp/赤龙ERP.

 * redragon-erp/赤龙ERP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.

 * redragon-erp/赤龙ERP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with redragon-erp/赤龙ERP.  If not, see <https://www.gnu.org/licenses/>.
 */
/**
 * @description GiteeUtil.java
 * @author dongbin
 * @version 
 * @copyright
 */

package com.global.util;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;

import org.apache.commons.lang.StringUtils;
import org.redragon.framework.util.JsonUtil;
import org.redragon.framework.util.RedisUtil;
import org.redragon.jersey.JerseyClient;

/**
 * @description
 * @date 2020年11月5日
 * @author dongbin
 * 
 */
public class GiteeUtil {

    public static String GITEE_TOKEN_CACHE_KEY = "GITEE_TOKEN";
    
    /**
     * 
     * @description 获取token
     * @date 2020年11月5日
     * @author dongbin
     * @return
     * @return String
     *
     */
    public static String getToken() {
        //获取redis中的token
        String token = "";
        
        try {
            token = RedisUtil.getValue(GiteeUtil.GITEE_TOKEN_CACHE_KEY);
        }catch(Exception e) {
        }
        
        //如果不存在则去gitee获取
        if(StringUtils.isBlank(token)) {
            //请求参数
            MultivaluedMap<String, String> params = new MultivaluedHashMap<String, String>();
            params.add("grant_type", "password");
            params.add("username", "dongbind@163.com");
            params.add("password", "forgetme1985");
            params.add("client_id", "7907abe80e4e32ba542b21092662e96d49ccecb77927c8137236df8b6956a4fb");
            params.add("client_secret", "61a24319e039ef9dae31caaf9b0037b90cf7a160ffaba56801737f151d28fca8");
            params.add("scope", "user_info projects pull_requests issues notes keys hook groups gists enterprises");
            //调用post
            JerseyClient jc = new JerseyClient(true);
            String result = jc.post("https://gitee.com/oauth/token", params);
            //获取token
            token = JsonUtil.getValueByKey(result, "access_token");
            
            //存入redis
            RedisUtil.setValue(GiteeUtil.GITEE_TOKEN_CACHE_KEY, token, 86000);
        }
        
        return token;
    }
    
    /**
     * 
     * @description 判断用户是否点击了star
     * @date 2020年11月5日
     * @author dongbin
     * @param username
     * @return
     * @return boolean
     *
     */
    public static boolean isClickStar(String username) {
        //验证参数
        if(StringUtils.isNotBlank(username)) {
            //获取token
            String token = GiteeUtil.getToken();
            if(StringUtils.isNotBlank(token)) {
                for(int a=1;a<=20;a++) {
                    //调用get
                    JerseyClient jc = new JerseyClient(true);
                    String result = jc.get("https://gitee.com/api/v5/repos/redragon/redragon-erp/stargazers?access_token="+token+"&page="+a+"&per_page=100");
                    //获取star用户列表
                    List<Map> list = JsonUtil.jsonToList(result, Map.class);
                    //如果用户列表不存在则退出循环
                    if(list==null||list.size()==0) {
                        break;
                    }
                    for(Map<String, String> map: list) {
                        if(map.get("login").equals(username)) {
                            return true;
                        }
                    }
                }
            }
        }
        
        return false;
    }
    
    /**
     * 
     * @description 私信发送erp账号
     * @date 2020年11月5日
     * @author dongbin
     * @param username
     * @param content
     * @return boolean
     *
     */
    public static boolean sendErpAccount(String username, String content) {
        //验证参数
        if(StringUtils.isNotBlank(username)&&StringUtils.isNotBlank(content)) {
            //获取token
            String token = GiteeUtil.getToken();
            if(StringUtils.isNotBlank(token)) {
                MultivaluedMap<String, String> params = new MultivaluedHashMap<String, String>();
                params.add("access_token", token);
                params.add("username", username);
                params.add("content", content);
                //调用post
                JerseyClient jc = new JerseyClient(true);
                String result = jc.post("https://gitee.com/api/v5/notifications/messages", params);
                //获取id
                String id = JsonUtil.getValueByKey(result, "id");
                if(StringUtils.isNotBlank(id)) {
                    return true;
                }
            }
        }
        
        return false;
    }
    
    
    
    /**
     * 
     * @description 获取token(授权方式)
     * @date 2020年11月5日
     * @author dongbin
     * @return
     * @return String
     *
     */
    public static String getTokenByAuth(String authCode, HttpServletResponse response) {
        //获取redis中的token
        String token = "";
        
        if(StringUtils.isNotBlank(authCode)) {
            //请求参数
            MultivaluedMap<String, String> params = new MultivaluedHashMap<String, String>();
            params.add("grant_type", "authorization_code");
            params.add("code", authCode);
            params.add("client_id", "7907abe80e4e32ba542b21092662e96d49ccecb77927c8137236df8b6956a4fb");
            params.add("client_secret", "61a24319e039ef9dae31caaf9b0037b90cf7a160ffaba56801737f151d28fca8");
            params.add("redirect_uri", "https://www.redragon-erp.com/erp/gitee/loginAuth");
            
            try {
                //调用post
                JerseyClient jc = new JerseyClient(true);
                String result = jc.post("https://gitee.com/oauth/token", params);
                //获取token
                token = JsonUtil.getValueByKey(result, "access_token");
            }catch(Exception e) {
            }
        }
        
        return token;
    }
    
    
    
    /**
     * 
     * @description 获取授权人的个人空间地址（授权方式）
     * @date 2021年1月15日
     * @author dongbin
     * @param token
     * @return
     * @return String
     *
     */
    public static String getLoginNameByAuth(String token) {
      //获取redis中的token
        String login = "";
        
        if(StringUtils.isNotBlank(token)) {
            
            try {
                //调用get
                JerseyClient jc = new JerseyClient(true);
                String result = jc.get("https://gitee.com/api/v5/user?access_token="+token);
                
                //获取login
                login = JsonUtil.getValueByKey(result, "login");
            }catch(Exception e) {
            }
        }
        
        return login;
    }
    
    
    
    /**
     * 
     * @description
     * @date 2021年1月15日
     * @author dongbin
     * @param response
     * @param postUrl
     * @param paramMap
     * @throws IOException
     * @return void
     *
     */
    public static void postGitee(HttpServletResponse response,String postUrl,Map<String, ?> paramMap) {
        try {
            response.setContentType( "text/html;charset=utf-8");   
            PrintWriter out = response.getWriter();  
            out.println("<html>");   
            out.println("<body>");   
            out.println("<form name='postSubmit' method='post' action='"+postUrl+"'>");  
            for (String key : paramMap.keySet()) {
                out.println("<input type='hidden' name='"+key+"' value='" + paramMap.get(key)+ "'>");
            }
            out.println("</form>");   
            out.println("<script>");   
            out.println("document.postSubmit.submit()");   
            out.println("</script>");   
            out.println("</body>");   
            out.println("</html>");
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
    
    
    
    public static void main(String[] args) {
        System.out.println(GiteeUtil.sendErpAccount("buzhidao11985", "感谢您对【赤龙ERP】的青睐；账号：redragon，密码：test"));
    }

}
